package com.csxh.web.filter;

import java.io.IOException;
import java.util.Enumeration;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

/**
 * 用于设置 HTTP 请求字符编码的过滤器，通过过滤器参数encoding指明使用何种字符编码,用于处理Html Form请求参数的中文问题
 */
public class ForwardHttpRequestFilter implements Filter {
	
	protected FilterConfig filterConfig = null;
	protected String urlPattern = "";

	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
			throws IOException, ServletException {
		if (this.urlPattern != null && this.urlPattern.length()>0){
		    //将原请求替换成forward请求
			HttpServletRequest request=(HttpServletRequest)servletRequest;
			String path=request.getServletPath();
			int pos=path.lastIndexOf(".");//*.jsp
			if(pos>-1){
				int index=this.urlPattern.lastIndexOf(".");//*.action
				if(index>-1){
					//进行替换
					path=path.substring(0, pos)+this.urlPattern.substring(index);
					
					//添加原请求的参数
					StringBuilder sb=new StringBuilder(path);
					
					String name;
					String value;
					Enumeration<String> parameterNames=request.getParameterNames();
					if(parameterNames.hasMoreElements()){
						name=parameterNames.nextElement();
						value=request.getParameter(name);
						sb.append("?").append(name).append("=").append(value).append("&");
						while(parameterNames.hasMoreElements()){
							name=parameterNames.nextElement();
							value=request.getParameter(name);
							sb.append(name).append("=").append(value).append("&");
						}
						sb=sb.deleteCharAt(sb.length()-1);
					}
					path=sb.toString();
					System.out.println(path);
					
					
					//将请求转发给新的请求
					request.getRequestDispatcher(path).forward(servletRequest, servletResponse);
				}
			}
			
		}
		
		filterChain.doFilter(servletRequest, servletResponse);
	}

	public void destroy() {
		
	}

	public void init(FilterConfig filterConfig) throws ServletException {
		this.filterConfig = filterConfig;
		this.urlPattern = filterConfig.getInitParameter("urlPattern");

	}
}